package com.rest.service;

import com.hcnow.common.utils.PasswordUtils;
import com.rest.model.User;
import com.rest.repository.UserRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    public User save(User user){
        PasswordUtils.INSTANCE.encryptPassword(user);
        return userRepository.save(user);
    }

    public List<User> findAll(){
        return userRepository.findAll();
    }

    public User findUserByUserId(String userId) {
        if(StringUtils.hasLength(userId)){
            return userRepository.findByName(userId);
        }
        return null;
    }

    public void deleteUserById(String id) {
        userRepository.deleteById(id);
    }

    public User updateUser(User entity) {
        User existedUser = userRepository.getOne(entity.getId());
        BeanUtils.copyProperties(entity,existedUser,new String[]{"id","createTime"});
        return userRepository.save(existedUser);
    }
}
